<template>
    <div class="g-page" v-if="pageData">
        <el-pagination 
            v-model:current-page="pageData.current" 
            v-model:page-size="pageData.size"
            :page-sizes="[20, 30, 50, 100]" 
            :layout="isMobile ? 'prev, pager, next' : 'sizes, prev, pager, next, jumper, total'" 
            :total="pageData.total"
            @update:page-size="handleSizeChange"
            @update:current-page="handleCurrentChange" 
            :small="isMobile"
            background
        />
    </div>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted } from 'vue'

const props = defineProps({
    pagination: {
        type: Object,
        required: true,
        default: () => ({
            current: 1,
            size: 20,
            total: 0
        })
    }
})

// 移动端检测
const windowWidth = ref(window.innerWidth)
const isMobile = computed(() => windowWidth.value <= 768)

// 监听窗口大小变化
const updateWidth = () => {
    windowWidth.value = window.innerWidth
}

onMounted(() => {
    window.addEventListener('resize', updateWidth)
})

onUnmounted(() => {
    window.removeEventListener('resize', updateWidth)
})

// 确保所有值都是数字类型
const pageData = computed(() => ({
    current: Number(props.pagination.current) || 1,
    size: Number(props.pagination.size) || 20,
    total: Number(props.pagination.total) || 0
}))

const emit = defineEmits(['update'])

const handleSizeChange = (size) => {
    emit('update', {
        size: Number(size),
        current: 1
    })
}

const handleCurrentChange = (current) => {
    emit('update', {
        size: Number(pageData.value.size),
        current: Number(current)
    })
}
</script>

<style scoped lang="less">
.g-page {
    padding-top: 12px;
    display: flex;
    padding-right: 20px;
    justify-content: flex-end;
    
    @media screen and (max-width: 768px) {
        padding-right: 0;
        justify-content: center;
    }
}
</style>